import 'dart:math';

import 'package:flutter/material.dart';

class KeyDemo1 extends StatefulWidget {
  @override
  _KeyDemoState createState() => _KeyDemoState();
}

/**
 * statelessWidget：UI变化参数存在Widget，所以不会有问题
    stateFullWidget：如果UI变化参数存在State，就会出bug
    如果删除widget不是最后一个，会对比key是不是一致，如果不设key，那key都是一致的，就会删掉最后一个widget
 */
class _KeyDemoState extends State<KeyDemo1> {
  List<Widget> items = [
    StlItem(//StlItem//StfulItem：如果UI变化参数存在State，就会出bug
      'aaaaa',
      //设置key2 没有key会有bug
      // key: ValueKey(111),//范型
    ),
    StlItem(//StlItem：UI变化参数存在Widget，所以不会有问题
      'bbbbb',
      // key: ObjectKey(Text('222')),//对象
    ),
    StlItem(
      'ccccc',
      // key: UniqueKey(),//可以保证key的唯一性（一旦使用，就不在使用element的更新了）
    ),
  ];

  @override
  Widget build(BuildContext context) {
    print(context.runtimeType);
    return Scaffold(
      appBar: AppBar(
        title: Text('keyDemo'),
      ),
      body: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: items,
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          setState(() {
            items.removeAt(0);
          });
        },
      ),
    );
  }
}

class StfulItem extends StatefulWidget {
  final title;
  //设置key1
  StfulItem(this.title, {Key key}) : super(key: key);

  @override
  _StfulItemState createState() => _StfulItemState();
}

class _StfulItemState extends State<StfulItem> {
  final _color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      color: _color,
      child: Text(widget.title),
    );
  }
}

//做一个正方形!
class StlItem extends StatelessWidget {
  final title;
  StlItem(this.title);
  final _color = Color.fromRGBO(
      Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);
  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      height: 100,
      color: _color,
      child: Text(title),
    );
  }
}
